using System;
using System.Collections.Generic;
using System.Text;

using SBPweb.Modules.Modularity;

namespace SBPweb.Contracts.Implementation
{
	/// <summary>
	/// Class of PersistableList
	/// </summary>
	public class PersistableList : List<string>, IPersistable
	{
		#region Private members

		private string pPersistencyKey;
		private IPersistable pParent;
		private IStatePersistenceService pPersistenceService;

		#endregion

		#region Constructor logic

		/// <summary>
		/// Constructor of PersistableList
		/// </summary>
		/// <param name="persistencyKey">persistency key</param>
		/// <param name="parent">parent</param>
		/// <param name="persistenceService">persistency service</param>
		public PersistableList(string persistencyKey, IPersistable parent, IStatePersistenceService persistenceService)
		{
			pParent = parent;
			pPersistenceService = persistenceService;
			if (!string.IsNullOrEmpty(persistencyKey))
			{
				pPersistencyKey = persistencyKey;
			}
			else
			{
				pPersistencyKey = this.GetType().Name;
			}
		}

		/// <summary>
		/// Constructor of PersistableList
		/// </summary>
		/// <param name="parent">parent</param>
		/// <param name="persistenceService">persistency service</param>
		public PersistableList(IPersistable parent, IStatePersistenceService persistenceService)
			: this(null, parent, persistenceService)
		{
		}

		#endregion

		#region IPersistable Members

		/// <summary>
		/// Persistency key
		/// </summary>
		public string PersistencyKey
		{
			get
			{
				return pPersistencyKey;
			}
		}

		/// <summary>
		/// Returns parent as Persistable
		/// </summary>
		public IPersistable ParentPersistable
		{
			get
			{
				return pParent;
			}
		}

		#endregion

		#region Public methods

		/// <summary>
		/// Save persistency
		/// </summary>
		public void SavePersistency()
		{
			if (pPersistenceService != null)
			{
				PersistencyDictionary state = new PersistencyDictionary(this);
				int i = 0;
				foreach (string value in this)
				{
					state.SetString((++i).ToString(), value);
				}
				pPersistenceService.Remove(this);
				pPersistenceService.Save(this, state);
			}
		}

		/// <summary>
		/// Load persistency
		/// </summary>
		public virtual void LoadPersistency()
		{
			if (pPersistenceService != null)
			{
				this.Clear();
				PersistencyDictionary state = pPersistenceService.Load(this);
				foreach (string key in state.Keys)
				{
					this.Add(state.GetString(key));
				}
			}
		}

		#endregion
	}
}
